package dse.messages.singleversion;

import dse.*;
import dse.messages.*;

public class ShareDataTransferMessageHandler
extends MessageSender
implements MessageHandler
{
	private DataObject dobj;
	private int shareIndex;
	private ShareDownloader shareDownloader;
	
	
	public ShareDataTransferMessageHandler (
			Experiment experiment, 
			DataObject dobj, 
			int shareIndex,
			ShareDownloader shareDownloader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.shareIndex = shareIndex;
		this.shareDownloader = shareDownloader;
	}
	
	public boolean acceptMessage (
			Message message
			)
	{
		if(message.purpose() == MessagePurpose.DataObjectUpdate)
			return true;
		else
			return !shareDownloader.isDoneDownloadingShares();			
	}
	
	public void messageReceived (
			ExperimentRecorder recorder, 
			Message message,
			double timeLeft
			)
	{
		recorder.debug(this, "msgRcvd: " + message, timeLeft);
		// All this really has to do is inform the share downloader that the
		// download has finished.
		if (message.messageType() != MessageType.ShareDataTransfer) {
			recorder.warn(
					"ShareDataTransferMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		//message.to().setSequence(Math.max(message.to().getSequence()+1, message.from().getSequence()));
		if(message.purpose() == MessagePurpose.DataObjectUpdate)
		{
			//message.to().sequence();
			Message m = super.createMessage(MessageType.UpdateConfirm, message.to(), message.from(), message.purpose(),
					new UpdateConfirmMessageHandler(experiment, dobj, shareIndex, true, shareDownloader));
			recorder.debug(this, "new msg: " + m, timeLeft);
			experiment.messageQueue().enqueueMessage(m, timeLeft);
		}
		else
			shareDownloader.shareDownloaded(
					recorder,
					message.from(),
					dobj, 
					shareIndex, 
					timeLeft
					);			
	}
	
	public void messageInterupted (
			ExperimentRecorder recorder, 
			Message message,
			double timeLeft
			)
	{
		recorder.debug(this, "msgIntrpt: " + message, timeLeft);
		
		if(message.purpose() == MessagePurpose.DataObjectUpdate)
		{
			//message.to().sequence();
			shareDownloader.shareUpdateFailed(
					recorder, dobj, shareIndex, timeLeft
					);
		}
		else
			shareDownloader.shareDownloadFailed(
				recorder, dobj, shareIndex, timeLeft
				);
	}
}
